package com.sunday.common.sharding.sphere.jdbc.study.base.sync.mixture;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description: synchronized修饰当前类和当前对象时不会互斥
 *
 * 【结论】可见，类锁和对象锁是相互独立的，互不相斥。
 *
 * @Author: zsy
 * @Create: 2023/4/4 15:23
 */
public class ClassAndObjectLock {

    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            ClassAndObjectLock.test1();
        }).start();

        new Thread(() -> {
            new ClassAndObjectLock().test2();
        }).start();
    }
    public static void test1(){
        synchronized (ClassAndObjectLock.class) {
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {}
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
        }
    }

    public void test2(){
        synchronized (this) {
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {}
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
        }
    }

}
